<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet">
    <link th:href="@{/css/plugins/bootstrap-select/bootstrap-select.min.css}" rel="stylesheet">
    <link th:href="@{/css/font-awesome.min.css}" rel="stylesheet">
    <link th:href="@{/css/animate.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
</head>
<body>
<div class="row">
    <div class="col-sm-12">
        <div class="ibox-content">
            <form class="form-horizontal m-t" id="commentForm" autocomplete="off">
                <div class="form-group">
                    <label class="col-sm-3 control-label">文件目录：</label>
                    <div class="col-sm-8">
                        <select class="selectpicker" id="catalogueId" name="catalogueId" >
                            <option value="">请选择</option>
                            <option data-icon="fa fa-folder" th:each="catalogue,catalogueStat:${catalogueList}" th:value="${catalogue.catalogueId}"
                                    th:disabled="${catalogue.catalogueId eq 1}"
                                    th:text="${catalogue.catalogueName}"></option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 control-label">上传附件：</label>
                    <div class="col-sm-8">
                        <div class="btn-toolbar" role="toolbar">
                            <div class="btn-group">
                                <div type="button" class="btn btn-default" id="i_select_files">
                                    <span class="glyphicon glyphicon-plus-sign"></span> 添加文件</div>
                            </div>
                        </div>
                        <div id="i_error_tips" class="alert alert-warning alert-dismissable" style="display: none">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <strong> 提示： </strong> <span class="text-message"></span>
                        </div>
                        <table id="data_table" class="table tablesorter" style="display: none">
                            <thead>
                            <tr><th>文件</th>
                                <th>进度</th>
                                <th>大小</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="bootstrap-stream-container">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="form-group form-button">
                    <div class="col-sm-12 col-sm-offset-5">
                        <button class="btn btn-success hidden" type="button">提交</button>
                        <!--<button class="btn btn-default cancel" type="button" >取消</button>-->
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/stream-v1.js}"></script>
<script th:src="@{/js/plugins/layer/layer.js}"></script>
<script th:src="@{/js/plugins/bootstrap-select/bootstrap-select.js}"></script>
<script th:src="@{/js/plugins/bootstrap-select/defaults-zh_CN.js}"></script>
<script th:inline="javascript">
    /**
     * 配置文件（如果没有默认字样，说明默认值就是注释下的值）
     * 但是，on*（onSelect， onMaxSizeExceed...）等函数的默认行为
     * 是在ID为i_stream_message_container的页面元素中写日志
     */

    //已上传的附件ID数组
    var ids = [];
    var config = {
        enabled: true, /** 是否启用文件选择，默认是true */
        customered: true,
        multipleFiles: true, /** 是否允许同时选择多个文件，默认是false */
        autoRemoveCompleted: false, /** 是否自动移除已经上传完毕的文件，非自定义UI有效(customered:false)，默认是false */
        autoUploading: true, /** 当选择完文件是否自动上传，默认是true */
        fileFieldName: "FileData", /** 相当于指定<input type="file" name="FileData">，默认是FileData */
        maxSize: 2147483648, /** 当_t.bStreaming = false 时（也就是Flash上传时），2G就是最大的文件上传大小！所以一般需要 */
        simLimit: 10000, /** 允许同时选择文件上传的个数（包含已经上传过的） */
        // extFilters: [".txt", ".gz", ".jpg", ".png", ".jpeg", ".gif", ".avi", ".html", ".htm"], /** 默认是全部允许，即 [] */
        browseFileId : "i_select_files", /** 文件选择的Dom Id，如果不指定，默认是i_select_files */
        browseFileBtn : "<div>请选择文件</div>", /** 选择文件的按钮内容，非自定义UI有效(customered:false) */
        // dragAndDropArea: "i_stream_dropzone",
        filesQueueId : "i_stream_files_queue", /** 文件上传进度显示框ID，非自定义UI有效(customered:false) */
        filesQueueHeight : 450, /** 文件上传进度显示框的高，非自定义UI有效(customered:false)，默认450px */
        tokenURL :[[${ctx}]]+"/tk",
        uploadURL:[[${ctx}]]+"/upload",
        postVarsPerFile:{"code":'ROLE_ADMIN'},
        messagerId : "i_stream_message_container", /** 消息框的Id，当没有自定义onXXX函数，系统会显示onXXX的部分提示信息，如果没有i_stream_message_container则不显示 */
//		frmUploadURL : "http://customers.duapp.com/fd;", /** Flash上传的URI */
//      uploadURL : "http://customers.duapp.com/upload",
        onSelect: function(files) {
            //console && console.log("-------------onSelect-------------------");
            //console && console.log(files);
            //console && console.log("-------------onSelect-------------------End");
        },
        onMaxSizeExceed: function(file) {
            //console && console.log("-------------onMaxSizeExceed-------------------");
            //console && console.log(file);
            $('#i_error_tips').show();
            $("#i_error_tips > span.text-message").append("文件[name="+file.name+", size="+file.formatSize+"]超过文件大小限制‵"+file.formatLimitSize+"‵，将不会被上传！<br>");
            //console && console.log("-------------onMaxSizeExceed-------------------End");
        },
        onFileCountExceed : function(selected, limit) {
            //console && console.log("-------------onFileCountExceed-------------------");
            //console && console.log(selected + "," + limit);
            $('#i_error_tips').show();
            $("#i_error_tips > span.text-message").append("同时最多上传<strong>"+limit+"</strong>个文件，但是已选择<strong>"+selected+"</strong>个<br>");
            //console && console.log("-------------onFileCountExceed-------------------End");
        },
        onExtNameMismatch: function(info) {
            //console && console.log("-------------onExtNameMismatch-------------------");
            //console && console.log(info);
            $('#i_error_tips').show();
            $("#i_error_tips > span.text-message").append("<strong>"+info.name+"</strong>文件类型不匹配[<strong>"+info.filters.toString() + "</strong>]<br>");
            //console && console.log("-------------onExtNameMismatch-------------------End");
        },
        onRepeatedFile: function(file) {
            // console.log("文件： " + file.name + " 大小：" + file.size + "已存在于上传队列中");
            // $('#i_error_tips').show();
            // $("#i_error_tips > span.text-message").append("文件： " + file.name
            //     + " 大小：" + file.size + "已存在于上传队列中");
            return true;
        },
        onAddTask: function(file) {
            $('#data_table').show();
            var str = '<tr id="' + file.id + '" class="template-upload fade in">' +
                '<td><span class="preview">'+file.name+'</span></td>' +
                '<td>'+
                '    <div><span class="label label-info">进度：</span> <span class="message-text"></span></div>' +
                '    <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
                '			<div class="progress-bar progress-bar-success" title="" style="width: 0%;"></div>' +
                '		</div>' +
                '</td>' +
                '<td>' +
                '<p class="size">' + file.formatSize + '</p>' +
                '</td>' +
                '<td>' +
                '<div class="glyphicon glyphicon-remove" style="cursor: pointer" onclick="deleteFile(\'' + file.id + '\')"><i></i></div>' +
                '</td>' +
                '</tr>';
            $("#bootstrap-stream-container").append(str);
        },
        onUploadProgress: function(file) {
            //console && console.log("-------------onUploadProgress-------------------");
            //console && console.log(file);

            var $bar = $("#"+file.id).find("div.progress-bar");
            $bar.css("width", file.percent + "%");
            var $message = $("#"+file.id).find("span.message-text");
            $message.text("已上传:" + file.formatLoaded + "/" + file.formatSize + "(" + file.percent + "%" + ") 速  度:" + file.formatSpeed);

            // var $total = $("#stream_total_progress_bar");
            // $total.find("div.progress-bar").css("width", file.totalPercent + "%");
            // $total.find("span.stream_total_size").html(file.formatTotalLoaded + "/" + file.formatTotalSize);
            // $total.find("span.stream_total_percent").html(file.totalPercent + "%");

            //console && console.log("-------------onUploadProgress-------------------End");
        },
        onStop: function() {
            //console && console.log("-------------onStop-------------------");
            //console && console.log("系统已停止上传！！！");
            //console && console.log("-------------onStop-------------------End");
        },
        onCancel: function(file) {
            //console && console.log("-------------onCancel-------------------");
            //console && console.log(file);

            $("#"+file.id).remove();

            // var $total = $("#stream_total_progress_bar");
            // $total.find("div.progress-bar").css("width", file.totalPercent + "%");
            // $total.find("span.stream_total_size").text(file.formatTotalLoaded + "/" + file.formatTotalSize);
            // $total.find("span.stream_total_percent").text(file.totalPercent + "%");
            //console && console.log("-------------onCancel-------------------End");
        },
        onCancelAll: function(numbers) {
            //console && console.log("-------------onCancelAll-------------------");
            //console && console.log(numbers + " 个文件已被取消上传！！！");
            $('#i_error_tips').show();
            $("#i_error_tips > span.text-message").append(numbers + " 个文件已被取消上传！！！");
            //console && console.log("-------------onCancelAll-------------------End");
        },
        onComplete: function(file) {
            //console && console.log("-------------onComplete-------------------");
            $('.btn-success').removeClass("hidden");

            console.log(JSON.parse(file.msg).id);
            ids.push(JSON.parse(file.msg).id);


            /** 100% percent */
            var $bar = $("#"+file.id).find("div.progress-bar");
            $bar.css("width", file.percent + "%");
            var $message = $("#"+file.id).find("span.message-text");
            $message.text("已上传:" + file.formatLoaded + "/" + file.formatSize + "(" + file.percent + "%" + ")");

            /** modify the total progress bar */
            // var $total = $("#stream_total_progress_bar");
            // $total.find("div.progress-bar").css("width", file.totalPercent + "%");
            // $total.find("span.stream_total_size").text(file.formatTotalLoaded + "/" + file.formatTotalSize);
            // $total.find("span.stream_total_percent").text(file.totalPercent + "%");

            //console && console.log("-------------onComplete-------------------End");
        },
        onQueueComplete: function(msg) {
            console.log(msg);
            //console && console.log("-------------onQueueComplete-------------------");
            //console && console.log("-------------onQueueComplete-------------------End");
        },
        onUploadError: function(status, msg) {
            //console && console.log("-------------onUploadError-------------------");
            //console && console.log(msg + ", 状态码:" + status);
            $('#i_error_tips').show();
            $("#i_error_tips > span.text-message").append(msg + ", 状态码:" + status);

            //console && console.log("-------------onUploadError-------------------End");
        }
    };
    var _t = new Stream(config);
    /** 不支持拖拽，隐藏拖拽框 */
    if (!_t.bDraggable) {
        $("#i_stream_dropzone").hide();
    }

    /** Flash最大支持2G */
    if (!_t.bStreaming) {
        _t.config.maxSize = 2147483648;
    }

    /**
     * 删除文件
     */
    function deleteFile(id){
        parent.layer.confirm("确认删除附件？",{btn: ['确定', '取消'], title: "提示"},function (index) {
            $('#'+id).remove();
            parent.layer.close(index);
        });
    }


    /**
     * 绑定保存按钮点击事件，提交表单
     */
    $('.btn-success').bind('click',function(){
        //目录ID
        var catalogueId = $('#catalogueId').val();
        //将附件保存到指定目录下
        $.ajax({
            type:'post',
            url:[[${ctx}]]+"/attachmentCatalogue/save.do",
            cache: false,
            data:{catalogueId:catalogueId,attachmentIds:ids.toString()},
            dataType:'json',
            success:function(data){
                if(data.code === 200){
                    parent.layer.msg('附件保存成功',{icon: 1});

                }else{
                    parent.layer.msg('附件保存失败', {icon: 2});
                }
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            }
        })
    })
</script>
</body>
</html>